<template>
  <!-- 管理员设置 begin -->
  <div class="main main-manager" id="main_manager">
    <div class="main-bd">
      <div class="iv-filter" v-if="roless=='admin'">
        <div class="items">
          <div class="label">{{$t('m.role')}}</div>
          <Select v-model="manageType" class="ivu-form-control" :placeholder="this.$t('m.role')">
            <Option value="">{{$t('m.entire')}}</Option>
            <Option v-for="(item, index) in types" :key="index" :value="item.type">{{ item.desc }}</Option>
          </Select>
        </div>
        <div class="items">
          <div class="label">{{$t('m.qǐngshūrùzhànghào')}}</div>
          <Input v-if="isShow" type="text" class="ivu-input-w200" v-model="accs" :placeholder="$t('m.qǐngshūrùzhànghào')" />
        </div>
        <br>
        <div style="padding:15px 0; clear: both;">
          <Button class="parameter_button" style="margin-right:30px;" @click="emptyQueryInfo">{{$t('m.recycle')}}</Button>
          <Button class="parameter_button" type="primary" @click="getManagers()">{{$t('m.cháxún')}}</Button>
          <Button type="primary" icon="md-add" class="btn-add" @click="adminModalAdd('formValidate')">{{$t('m.add')}}</Button>
        </div>
      </div>
      <div class="content-wrap">
        <div class="list" id="manager_list">
          <Table border :columns="accountTable" :data="managerList">
            <template slot-scope="{ row }" slot="role">
              <strong>{{roleNameObj[row.roleName]  }}</strong>
            </template>
            <template slot-scope="{ row }" slot="status">
              <strong v-if="row.enable==1">{{$t('m.kāiqǐ')}}</strong>
              <strong v-else>{{$t('m.guānbì')}}</strong>
            </template>
            <template slot-scope="{ row, index }" slot="action">
              <Button type="primary" style="margin-right:20px;" @click="editAdminModal(row)" v-if="enableSet">{{$t('m.edRo')}}</Button>
              <Button type="error" @click="deleteEvent(row)" v-if="enableSet">{{$t('m.delete')}}</Button>
            </template>
          </Table>
          <div class="managerPage_box">
            <Page :total="accountPageSum" :current.sync="accountPages" :page-size-opts="[1, 10, 20, 40, 80, 100]" show-total show-elevator show-sizer @on-change="accountWritePage" @on-page-size-change="accountClickPage" style="margin: 15px 0;"></Page>
          </div>
        </div>
        <!-- 管理员列表end -->
        <!-- 添加管理员弹出层 begin -->
        <div class="modal fade" id="addManagerModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
          <div class="modal-dialog" style="width: 540px;">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">{{$t('m.add')}}</h4>
              </div>
              <form action="" class="form form-horizontal info-form" id="addManagerForm">
                <div class="modal-body">
                  <ul>
                    <li>{{$t('m.role')}}：<select v-model="addType" name="type" class="form-control" id="add_manager_type" @change="handleRoleChange">
                        <option value="">select a role</option>
                        <option v-for="(item, index) in types" :value="item.type" :key="index">{{item.desc}}</option>
                      </select>
                    </li>
                    <li v-show="showStatus">Superior：<select v-model="parentId" name="type" class="form-control">
                        <option value="0">Select a Superior</option>
                        <option v-for="(item, index) in parentList" :value="item.id" :key="index">{{item.name}}</option>
                      </select>
                    </li>
                    <li>username：<input type="text" class="form-control" id="add_manager_name" name="name" required></li>
                    <li>password：<input type="password" class="form-control" id="add_manager_password" name="password" required></li>
                    <li>
                    </li>
                  </ul>
                </div>
                <div class="modal-footer">
                  <Button type="error" class="btn btn-default" data-dismiss="modal" @click="cancel">close</Button>
                  <Button type="primary" class="btn btn-success" id="add_manager_btn" @click="addManager">add</Button>
                </div>
              </form>
            </div>
          </div>
        </div>
        <!-- 添加管理员弹出层 end -->
      </div>
    </div>
    <div>
      <Modal v-model="adminModal" :width="976" :title="this.$t('m.edRo')" @on-ok="ok()" @on-cancel="adminModalCancel" :footer-hide="true">
        <Form ref="formValidate" :model="formValidate" :rules="!createAccountType? ruleValidateEdit :ruleValidate" :label-width="100" class="userInfo_box">
          <FormItem :label="this.$t('m.Account')" prop="account">
            <Input :disabled="!createAccountType"  v-model="formValidate.account" :placeholder="this.$t('m.qǐngshūrùzhànghào')"></Input>
          </FormItem>
          <FormItem :label="this.$t('m.mìmǎ')" prop="OldPassword">
            <Input type="password" v-model="formValidate.OldPassword" :placeholder="this.$t('m.qǐngshūrùmìmǎ')"></Input>
          </FormItem>
          <FormItem :label="this.$t('m.quèrènmìmǎ')" prop="password">
            <Input type="password" v-model="formValidate.password" :placeholder="this.$t('m.Qǐngzàicìshūrùmìmǎ')"></Input>
          </FormItem>
          <FormItem :label="this.$t('m.role')" prop="roleName">
            <Select v-model="formValidate.roleName" :placeholder="this.$t('m.qǐngxuǎnzéjuésè')">
              <!-- <Option value="beijing">全部</Option> -->
              <Option v-for="(item ,index) in types" :value="item.type">{{item.desc}}</Option>
            </Select>
          </FormItem>
          <FormItem :label="this.$t('m.miáoshù')" prop="description">
            <Input v-model="formValidate.description" type="textarea" :autosize="{minRows: 2,maxRows: 5}" :placeholder="this.$t('m.qǐngshūrùmiáoshù')"></Input>
          </FormItem>
          <FormItem :label="this.$t('m.uSta')" prop="enable">
            <RadioGroup v-model="formValidate.enable">
              <Radio :label="1">{{$t('m.kāiqǐ')}}</Radio>
              <Radio :label="0">{{$t('m.guānbì')}}</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem style="text-align: right;">
            <Button @click="handleReset('formValidate')">{{$t('m.cancle')}}</Button>
            <Button type="primary" @click="handleSubmit('formValidate')" style="margin-left: 20px">{{$t('m.submit')}}</Button>
          </FormItem>
        </Form>
      </Modal>
    </div>

    <Modal v-model="deleteModel" @on-ok="deleteAdminModal" @on-cancel="">
      <p style="font-size: 20px"> {{ $t("m.areyoudel") }} </p>
    </Modal>
  </div>
  <!-- 管理员设置 end -->
</template>

<script>
import { mapGetters } from 'vuex';
export default {
  data () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('m.qǐngshūrùmìmǎ')));
      } else {
        if (this.formValidate.password !== '') {
          // 对第二个密码框单独验证
          this.$refs.formValidate.validateField('password');
        }
        callback();
      }
    };
    const validatePassCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('m.Qǐngzàicìshūrùmìmǎ')));
      } else if (value !== this.formValidate.OldPassword) {
        callback(new Error(this.$t('m.liǎcìmìmǎbùyīyàng')));
      } else {
        callback();
      }
    };
    return {
      accountTable: [
        {
          title: this.$t('m.sortNo'),
          key: 'id',
          align: 'center',
          sortable: true
        },
        {
          title: this.$t('m.Account'),
          align: 'center',
          key: 'account'
        },
        {
          title: this.$t('m.role'),
          slot: 'role',
          align: 'center',

        },
        {
          title: this.$t('m.miáoshù'),
          align: 'center',
          key: 'description'
        },

        {
          title: this.$t('m.status'),
          align: 'center',
          slot: 'status',
        },

        {
          title: this.$t('m.chuàngjiànshíjiān'),
          align: 'center',
          key: 'ctime',
          sortable: true
        },
        {
          title: this.$t('m.operate'),
          align: 'center',
          slot: 'action',
          width: 220,
          align: 'center'
        }
      ],
      deleteModel: false,
      deleteId: '',
      createAccountType: false,
      roless: '',
      isShow: false,
      value: '',
      adminModal: false,
      type: -1,
      addType: '',
      parentId: 0,
      showStatus: false,
      id: '',
      managerList: [],
      pageNumber:1,
      accountPageSize:10,
      accountPages:1,
      accountPageSum:0,  
      accs: '',
      maps: {
        '5': 13,
        '10': 14,
        '12': 15,
        '17': 18,
        '19': 20
      },
      parentTypes: [],
      parentList: [],

      formValidate: {
        account: '',
        OldPassword: '',
        password: '',
        roleName: '',
        enable: 1,
        description: '',
      },
      ruleValidate: {
        account: [
          { required: true, message: this.$t('m.qǐngshūrùzhànghào'), trigger: 'blur' }
        ],
        OldPassword: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validatePassCheck, trigger: 'blur' }
        ],
        roleName: [
          { required: true, message: this.$t('m.qǐngxuǎnzéjuésè'), trigger: 'change' }
        ],
        description: [
          { required: false, message: this.$t('m.qǐngshūrùmiáoshù'), trigger: 'change' }
        ],

      },
      ruleValidateEdit: {
        account: [
          { required: false, message: this.$t('m.qǐngshūrùzhànghào'), trigger: 'blur' }
        ],
        OldPassword: [
          { required: false }
        ],
        password: [
          { required: false }
        ],
        roleName: [
          { required: true, message: this.$t('m.qǐngxuǎnzéjuésè'), trigger: 'change' }
        ],
        description: [
          { required: false, message: this.$t('m.qǐngshūrùmiáoshù'), trigger: 'change' }
        ],

      },
      types: [
        //管理员、初审信审、终审信审、信审主管、催收、催收-L、催收主管、财务、运营
        {          desc: this.$t('m.admin'),
          type: 'admin'
        },

        {          desc: this.$t('m.chushen'),
          type: 'checker'
        },        
        {          desc: this.$t('m.Finalreviewer'),
          type: 'checker_final'
        },       
        {          desc: this.$t('m.xìnshěnzhǔguǎn'),
          type: 'checker_leader'
        },
        {          desc: this.$t('m.kefu'),
          type: 'service'
        },

        {          desc: this.$t('m.yunying'),
          type: 'operator'
        },

        {          desc: this.$t('m.cszg'),
          type: 'reminder_leader'
        },

        {          desc: this.$t('m.s0'),
          type: 'reminder_s0'
        },

        {          desc: this.$t('m.s0l'),
          type: 'reminder_s0_leader'
        },

        {          desc: this.$t('m.s1'),
          type: 'reminder_s1'
        },

        {          desc: this.$t('m.s1l'),
          type: 'reminder_s1_leader'
        },
        {          desc: this.$t('m.s2'),
          type: 'reminder_s2'
        },

        {          desc: this.$t('m.s2l'),
          type: 'reminder_s2_leader'
        },
        {          desc: this.$t('m.m2'),
          type: 'reminder_m2'
        },
        {          desc: this.$t('m.m2l'),
          type: 'reminder_m2_leader'
        },
        {          desc: this.$t('m.m3'),
          type: 'reminder_m3'
        },
        {          desc: this.$t('m.m3l'),
          type: 'reminder_m3_leader'
        },

      ],
      role: ['管理员', '运营', '信审', '风控', '财务', '内催（1-3天）', '客服', '市场部', '采购', '催收主管', '外催1（4-15天）', '线下营销', '外催2（16-30天）'],
      roleNameObj: {
        'admin': this.$t('m.admin'),
        'checker': this.$t('m.chushen'),
        'service': this.$t('m.kefu'),
        'operator': this.$t('m.yunying'),
        'reminder_leader': this.$t('m.cszg'),
        'reminder_s0': this.$t('m.s0'),
        'reminder_s0_leader': this.$t('m.s0l'),
        'reminder_s1': this.$t('m.s1'),
        'reminder_s1_leader': this.$t('m.s1l'),
        'reminder_s2': this.$t('m.s2'),
        'reminder_s2_leader': this.$t('m.s2l'),
        'reminder_m2': this.$t('m.m2'),
        'reminder_m2_leader': this.$t('m.reminder_m2'),
        'reminder_m3': this.$t('m.m3'),
        'reminder_m3_leader': this.$t('m.m3l'),
        'black_query': this.$t('m.hēimíngdāncháxún'),
      },
      adminType: sessionStorage.roles,
      investorId: '',
      investorList: [], //所属客户列表
      investorVisible: false, //所属客户是否可见
      manageType: ''
    }
  },
  computed: {
    enableSet () {
      return this.adminType == 'admin' || this.adminType == 9;
    },
    ...mapGetters([
      'roles',
      'peacock',
      'account',
      'avatar'
    ])
  },
  watch: {
    addType: function () {
      if (this.addType == 5 || this.addType == 10 || this.addType == 12 || this.addType == 17 || this.addType == 19) {
        var _this = this;
        this.$http.post('/helsinki/admin/getManagers', { type: _this.maps[_this.addType] }).then(function (res) {
          if (res.data.errcode == 0) {
            _this.parentList = res.data.data.list;
          }
        }, function (err) {
          console.log(err);
        });
        this.showStatus = true;
      } else {
        this.showStatus = false;
      }
    },
    type: function () {
      if (this.type == 'reminder_s0' || this.type == 'reminder_s1' || this.type == 'reminder_s2' || this.type == 'reminder_m1' || this.type == 'reminder_m2' || this.type == 'reminder_m3') {
        var _this = this;
        var url1 = '/api/laocai/sys/account/list?' + 'roleName=' + _this.type + '_leader'
        this.$http.get(url1).then(function (res) {
          if (res.body.code == 0) {
            _this.parentList = res.body.result.list;
          }
        }, function (err) {
          console.log(err);
        });
        this.showStatus = true;
      } else {
        this.showStatus = false;
      }
    }
  },
  created () { },
  mounted () {
    this.roless = this.roles
    if (this.roless === 'admin') {
      this.getManagers();
    } else {
      this.getOne();
    }
    setTimeout(() => {
      this.isShow = true;
    }, 1)
  },
  methods: {
     accountWritePage(index){
       this.pageNumber = index 
       this.getManagers()
     },
       
    accountClickPage(index){
       this.accountPageSize = index
       this.getManagers()
    },
    deleteEvent (v) {
      this.deleteModel = true
      this.deleteId = v.id
    },
    // 删除
    deleteAdminModal () {
      this.$http.post('/api/laocai/sys/account/delete', {
        id: this.deleteId
      }).then((res) => {
        if (res.body.code == 0) {
          this.deleteId = ''
          this.$Message.info(this.$t('m.chénggōng'));
          this.getManagers();
        } else {
          alert(res.body.message);
        }

      });
    },
    adminModalAdd (name) {
      this.createAccountType = true
      this.adminModal = true
      setTimeout(() => {
        this.$refs[name].resetFields();             
      }, 10);
    },
    editAdminModal (item) {
      console.log(item, "信息啊")
      this.createAccountType = false
      this.formValidate.id = item.id
      this.formValidate.account = item.account
      this.formValidate.roleName = item.roleName
      this.formValidate.enable = item.enable
      this.formValidate.description = item.description
      this.adminModal = true
    },
    adminModalCancel () {
      this.$refs.formValidate.resetFields();
      this.$Message.info(this.$t('m.cancel'));
    },
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.createAccountType) {
            this.addManager()
          } else {
            this.addManagerEdit()
          }
        } else {
        }
      })
    },
    handleReset (name) {
      this.$refs[name].resetFields();      
      this.adminModal = false
    },
    emptyQueryInfo () {
      this.manageType = ''
      this.accs = ''
      this.getManagers();
    },
    userUsingEvent (id, v) {
      this.$http.post('/api/laocai/sys/account/business/update', {
        id: id,
        enable: v,
      }).then((res => {
        if (res.body.code == 0) {
          this.$Message.success('修改成功');
          this.getManagers()
        } else {
          this.$Message.warning(res.body.message);
        }
      }));
    },

    getOne () {
      var _this = this;
      var one = _this.account - center - team
      var url1 = '/api/laocai/sys/account/list' + '?' + 'account' + '=' + one
      this.$http.get(url1).then(function (res) {
        if (res.body.code == 0) {
          var ress = res.body.result.list
          _this.managerList = ress;
        }
      }, function (err) {
        console.log(err);
      });
    },
    getManagerType () {
      $.get('/helsinki/admin/getManagerType')
        .then(({ data: { list } }) => {
          this.types = list;
        })
    },
    addManager () {
      this.$http.post('/api/laocai/sys/account/add', {
        account: this.formValidate.account,
        password: this.formValidate.password,
        roleName: this.formValidate.roleName,
        enable: this.formValidate.enable,
        description: this.formValidate.description,
      }).then((res => {
        if (res.body.code == 0) {
          this.$Message.success(this.$t('m.add') + this.$t('m.errorCode' + res.body.code));
          this.adminModal = false
          this.getManagers();
        } else {
          this.$Message.success(this.$t('m.add') + this.$t('m.errorCode' + res.body.code));
        }
      }));
    },
    getManagers () {
      let param = {},
        query = ''
      param.pageNumber=this.pageNumber,
      param.pageSize=this.accountPageSize,
      param.roleName=this.manageType,
      param.account=this.accs
      Object.keys(param).forEach((item, index) => {
        if (param[item]) {
          query += `${index === 0 ? '' : '&'}${item}=${param[item]}`;
        }
      });
      var url = `/api/laocai/sys/account/list?${query}`
      this.$http.get(url).then(function (res) {
        if (res.body.code == 0) {
          var data = res.body.result
          this.accountPageSum = data.size
          if (data.list == null) {            
            this.managerList = []
          }else{
            this.managerList = data.list;
          }
        }
      }, function (err) {
        console.log(err);
      });
    },
    render (id, type) {
      var _this = this;
      this.$Modal.confirm({
        render: (h) => {
          return h('Input', {
            props: {
              type: 'password',
              value: this.value,
              autofocus: true,
              required: true,
              placeholder: 'Please enter your name...'
            },
            on: {
              click: function () {
                input: (val) => {
                  this.value = val;
                  if (val == '') {
                    _this.$Message.info('请输入新密码');
                    return false;
                  } else {
                    this.$http.post('/helsinki/admin/updatePassword', {
                      id: id,
                      parentId: this.parentId,
                      type: type,
                      password: val
                    }).then(function (res) {
                      if (res.data.errcode == 0) {
                        _this.$Message.info(res.data.info);
                      }
                    }, function (err) {
                      // _this.$Message.info(err);
                    });
                  }
                }
              }
            }
          })
        }
      })
    },
    updatePasswordOrType (id, num) {
      if (num == 0) { // 编辑
        var role = ['超级管理员', '运营组', '风控组成员（初审）', '风控组组长（二审）', '财务组', '催收组', '客服', '市场部', '采购部', '催收主管', '外包公司', '线下营销'];
        old_type = $('#manager_type_td_' + id).attr('data-type'),
          old_type_text = $('#manager_type_td_' + id).html(),
          o = '';
        $('#manager_type_td_' + id).html('<form class="form-inline"><select class="form-control" id="update_type_select_' + id + '" style="width: 150px;"><option value="' + old_type + '">' + old_type_text + '</option></select>&nbsp;<button class="btn btn-success" id="update_type_save_' + id + '" onclick="UpdatePasswordOrType(' + id + ',' + num + ');">保存</button>&nbsp;<button class="btn btn-danger" id="update_type_cancel_' + id + '">取消</button>');
        for (var i = 0,
          len = role.length; i < len; i++) {
          if (old_type != i) {
            o += '<option value="' + i + '">' + role[i] + '</option>';
          }
        }
        $('#update_type_select_' + id).append(o);
        $('#update_type_' + id).hide();

        // 取消
        $('#update_type_cancel_' + id).click(function () {
          $('#manager_type_td_' + id).html(old_type_text);
          $('#update_type_' + id).show();
        });
      } else if (num == 1) {
        $('#update_password_' + id).hide();
        var time = $('#manager_password_td_' + id).html();
        $('#update_password_' + id).attr('data-time', time);
        $('#manager_password_td_' + id).html('<form class="form-inline"><input class="form-control" type="password" id="update_password_input_' + id + '" style="width: 150px;" placeholder="输入新密码">&nbsp;<button class="btn btn-success" id="update_password_save_' + id + '" onclick="UpdatePasswordOrType(' + id + ',' + num + ');">保存</button>&nbsp;<button class="btn btn-danger" id="update_password_cancel_' + id + '">取消</button>');

        // 取消
        $('#update_password_cancel_' + id).click(function () {
          $('#manager_password_td_' + id).html(time);
          $('#update_password_' + id).show();
        });
      }
    },
    addManagerEdit () {
      this.$http.post('/api/laocai/sys/account/update', {
        id: this.formValidate.id,
        nickname: this.formValidate.nickname,
        password: this.formValidate.password,
        roleName: this.formValidate.roleName,
        enable: this.formValidate.enable,
        description: this.formValidate.description,
      }).then((response) => {
        // debugger
        this.$Message.success(this.$t('m.xiūgǎi') + this.$t('m.errorCode' + response.body.code));
        // setTimeout(() => {
        this.adminModal = false

        // this.$Message.success('角色修改成功');
        // $('#adminModal').modal('hide');
        this.getManagers();

        // }, 300);
      }, error => {
        this.$Message.success(this.$t('m.xiūgǎi') + this.$t('m.errorCode' + response.body.code));
      });
    },
    cancel () {
      this.$Message.info(this.$t('m.cancel'));
    },

    handleRoleChange (e) {
      let value = e.target.value;
      if (value == 16) {
        this.investorVisible = true;
        // this.getInvestorList();
      } else {
        this.investorVisible = false;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../static/style.css";
@import "../static/common.scss";

.items {
  display: inline-block;
  margin-bottom: 10px;
  margin-right: 20px;
  width: 200px;
  float: left;

  .label {
    overflow: hidden;
    white-space: inherit;
    text-align: right;
    color: #222;
    font-size: 14px;
    margin-right: 10px;
  }
}

.userInfo_box {
  margin: 20px 50px;
}

.iv-filter {
  padding: 15px;
  overflow: hidden;
  .ivu-form-control {
    width: 200px;
  }
}

.btn-add {
  // margin: 15px 20px 0 0;
  float: right;
}

.investor-item {
  margin-top: 15px;
}

.admin-label {
  display: inline-block;
  width: 60px;
}
.buttonOpen {
  background: #19be6b;
  border: 1px #19be6b solid;
}
.buttonClose {
  background: #444;
  border: 1px #444 solid;
}
.managerPage_box{
  text-align: right;
}
</style>
